//
//  BlankViewController.swift
//  YYPBlankView
//
//  Created by YYPan on 2018/5/18.
//  Copyright © 2018年 YYPan. All rights reserved.
//

import UIKit
import MJRefresh

class BlankViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

	var type: String?
	
	private lazy var tableView: UITableView = {
		let table = UITableView(frame: self.view.bounds)
		table.delegate = self
		table.dataSource = self
		table.rowHeight = 50
		table.separatorStyle = .none
		let header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
			self?.reload()
		})
		header?.lastUpdatedTimeLabel.isHidden = true
		header?.stateLabel.isHidden = true
		table.mj_header = header
		return table
	}()
	
	private var dataSources = [String]()
	
    override func viewDidLoad() {
        super.viewDidLoad()
        title = type
		view.addSubview(tableView)
    }
	
	override func viewWillAppear(_ animated: Bool) {
		super.viewWillAppear(animated)
		tableView.mj_header.beginRefreshing()
	}
	
	private func reload() {
		// 模拟数据请求
		DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
			if self.dataSources.count == 0 {
				self.showBlankView()
			} else {
				self.tableView.removeBlankView()
			}
			self.tableView.mj_header.endRefreshing()
			self.tableView.reloadData()
		}
	}
	
	private func showBlankView() {
		switch type {
		case "没有网络":
			tableView.showBlankView(blankViewType: .noNetWork) { [weak self] in
				self?.dataSources = Array(repeating: "测试数据", count: 10)
				self?.tableView.mj_header.beginRefreshing()
			}
		case "没有数据":
			tableView.showBlankView(blankViewType: .noResults) { [weak self] in
				self?.dataSources = Array(repeating: "测试数据", count: 10)
				self?.tableView.mj_header.beginRefreshing()
			}
		case "没有搜索结果":
			tableView.showBlankView(blankViewType: .noSearchResults, reloadBlock: nil)
		default:
			break
		}
	}
	
	func numberOfSections(in tableView: UITableView) -> Int {
		return 1
	}
	
	func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		return dataSources.count
	}
	
	func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
		let cell = UITableViewCell()
		cell.textLabel?.text = dataSources[indexPath.row]
		return cell
	}
	
	func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
		tableView.deselectRow(at: indexPath, animated: true)
	}
}
